﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySoft.Data;
using Caifu.Fx;
using Itfort;
namespace Caifu.Datas
{
    public class SsoData
    {
        /// <summary>
        /// User数据操作类；
        /// </summary>
        public static readonly SsoData Instance = new SsoData();

        private readonly DbSession dbSession = new DbSession("Caifu");

        /// <summary>
        /// 根据Ticket（票据）获得相关单点登录信息
        /// </summary>
        /// <param name="ticket">票据</param>
        /// <returns></returns>
        public UserSso GetLoginInfoByTicket(Guid ticket)
        {
            return dbSession.Single<UserSso>(UserSso._.Ticket == ticket);
        }


        /// <summary>
        /// 根据用户ID返回其单点登录信息
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>单点登录信息</returns>
        public UserSso GetLoginInfoByUserId(Guid userId)
        {
            return dbSession.Single<UserSso>(UserSso._.UserId == userId);
        }

        /// <summary>
        /// 添加单点登录信息
        /// <param name="loginInfo">
        /// 单点登录对象
        /// </param>
        /// </summary>
        public void AddSsoInfo(Guid uid, Guid ticket)
        {
            UserSso sso = new UserSso();
            sso.Detach();
            sso.Id = Comb.NewComb();
            sso.UpdateTime = DateTime.Now;
            sso.Status = 0;
            sso.UserId = uid;
            sso.Ticket = ticket;
            dbSession.Save<UserSso>(sso);
        }

        /// <summary>
        /// 更新单点登录信息
        /// <param name="loginInfo">
        /// 单点登录对象
        /// </param>
        /// </summary>
        public void UpdateSsoInfo(Guid uid, Guid ticket)
        {
            dbSession.Update<UserSso>(new Field[] { UserSso._.Ticket, UserSso._.UpdateTime },
                new object[] { ticket, DateTime.Now }, UserSso._.UserId == uid);
        }
    }
}
